package com.plugin; /**
 * 插件管理器图形界面
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Date;
import java.util.Map;

public class PluginManagerGUI extends JFrame {
    private final PluginManager pluginManager;
    private final ServiceManager serviceManager;
    private JList<PluginInfo> pluginList;
    private DefaultListModel<PluginInfo> pluginListModel;
    private JTextArea pluginDetails;
    private JTextArea logArea;
    private JPanel serviceStatusPanel;

    // 操作按钮
    private JButton downloadButton;
    private JButton installButton;
    private JButton uninstallButton;
    private JButton startButton;
    private JButton stopButton;
    
    public PluginManagerGUI(PluginManager manager) {
        this.pluginManager = manager;
        this.serviceManager = ServiceManager.getInstance(pluginManager);
        
        initializeUI();
        setupEventListeners();
        refreshPluginList();
        updateServiceStatus();
        
        // 设置日志服务
        LogService logService = serviceManager.getService(LogService.class);
        logService.info("插件管理器已启动");
    }
    
    private void initializeUI() {
        setTitle("插件与服务管理器");
        setSize(900, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        
        // 左侧插件列表
        pluginListModel = new DefaultListModel<>();
        pluginList = new JList<>(pluginListModel);
        pluginList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        pluginList.setCellRenderer(new PluginListCellRenderer());
        
        JScrollPane listScrollPane = new JScrollPane(pluginList);
        listScrollPane.setPreferredSize(new Dimension(200, 0));
        
        // 中间插件详情和服务状态
        JPanel centerPanel = new JPanel(new BorderLayout());
        
        // 插件详情
        pluginDetails = new JTextArea();
        pluginDetails.setEditable(false);
        JScrollPane detailsScrollPane = new JScrollPane(pluginDetails);
        detailsScrollPane.setBorder(BorderFactory.createTitledBorder("插件详情"));
        
        // 服务状态
        serviceStatusPanel = new JPanel(new GridLayout(0, 1));
        serviceStatusPanel.setBorder(BorderFactory.createTitledBorder("当前激活的服务"));
        JScrollPane serviceScrollPane = new JScrollPane(serviceStatusPanel);
        serviceScrollPane.setPreferredSize(new Dimension(0, 150));
        
        centerPanel.add(detailsScrollPane, BorderLayout.CENTER);
        centerPanel.add(serviceScrollPane, BorderLayout.SOUTH);
        
        // 底部日志区域和按钮
        JPanel bottomPanel = new JPanel(new BorderLayout());
        
        // 日志区域
        logArea = new JTextArea();
        logArea.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(logArea);
        logScrollPane.setPreferredSize(new Dimension(0, 120));
        logScrollPane.setBorder(BorderFactory.createTitledBorder("操作日志"));
        
        // 按钮面板
        JPanel buttonPanel = new JPanel();
        downloadButton = new JButton("下载插件");
        installButton = new JButton("安装插件");
        uninstallButton = new JButton("卸载插件");
        startButton = new JButton("启动插件");
        stopButton = new JButton("停止插件");
        
        buttonPanel.add(downloadButton);
        buttonPanel.add(installButton);
        buttonPanel.add(uninstallButton);
        buttonPanel.add(startButton);
        buttonPanel.add(stopButton);
        
        bottomPanel.add(buttonPanel, BorderLayout.NORTH);
        bottomPanel.add(logScrollPane, BorderLayout.CENTER);
        
        // 组装主面板
        mainPanel.add(listScrollPane, BorderLayout.WEST);
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);
        
        add(mainPanel);
        
        // 初始禁用所有按钮
        updateButtonStates();
    }
    
    private void setupEventListeners() {
        // 插件列表选择事件
        pluginList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                updatePluginDetails();
                updateButtonStates();
            }
        });
        
        // 按钮事件
        downloadButton.addActionListener(e -> downloadPlugin());
        installButton.addActionListener(e -> installSelectedPlugin());
        uninstallButton.addActionListener(e -> uninstallSelectedPlugin());
        startButton.addActionListener(e -> startSelectedPlugin());
        stopButton.addActionListener(e -> stopSelectedPlugin());
        
        // 添加插件监听器，用于更新界面
        pluginManager.addPluginListener(new PluginAdapter() {
            @Override
            public void pluginInstalled(PluginEvent event) {
                refreshPluginList();
                updateServiceStatus();
                log(event.getPlugin().getName() + " 已安装");
            }
            
            @Override
            public void pluginUninstalled(PluginEvent event) {
                refreshPluginList();
                updateServiceStatus();
                log(event.getPlugin().getName() + " 已卸载");
            }
            
            @Override
            public void pluginStarted(PluginEvent event) {
                refreshPluginList();
                updateServiceStatus();
                log(event.getPlugin().getName() + " 已启动");
            }
            
            @Override
            public void pluginStopped(PluginEvent event) {
                refreshPluginList();
                updateServiceStatus();
                log(event.getPlugin().getName() + " 已停止");
            }
            
            @Override
            public void pluginDownloaded(PluginEvent event) {
                refreshPluginList();
                log("插件下载完成");
            }
        });
    }
    
    /**
     * 刷新插件列表
     */
    private void refreshPluginList() {
        SwingUtilities.invokeLater(() -> {
            pluginListModel.clear();
            for (PluginInfo info : pluginManager.getAvailablePlugins()) {
                pluginListModel.addElement(info);
            }
        });
    }
    
    /**
     * 更新插件详情
     */
    private void updatePluginDetails() {
        PluginInfo selected = pluginList.getSelectedValue();
        if (selected != null) {
            StringBuilder details = new StringBuilder();
            details.append("名称: ").append(selected.getName()).append("\n\n");
            details.append("ID: ").append(selected.getId()).append("\n\n");
            details.append("版本: ").append(selected.getVersion()).append("\n\n");
            details.append("描述: ").append(selected.getDescription()).append("\n\n");
            details.append("下载地址: ").append(selected.getDownloadUrl()).append("\n\n");
            
            // 检查是否已安装
            Plugin installedPlugin = pluginManager.getPluginById(selected.getId());
            if (installedPlugin != null) {
                details.append("状态: 已安装\n");
                details.append("运行状态: ").append(
                    pluginManager.isPluginRunning(selected.getId()) ? "运行中" : "已停止"
                ).append("\n");
            } else {
                details.append("状态: 未安装\n");
            }
            
            pluginDetails.setText(details.toString());
        } else {
            pluginDetails.setText("请选择一个插件查看详情");
        }
    }
    
    /**
     * 更新按钮状态
     */
    private void updateButtonStates() {
        PluginInfo selected = pluginList.getSelectedValue();
        boolean hasSelection = selected != null;
        
        if (hasSelection) {
            Plugin installedPlugin = pluginManager.getPluginById(selected.getId());
            boolean isInstalled = installedPlugin != null;
            boolean isRunning = isInstalled && pluginManager.isPluginRunning(selected.getId());
            
            downloadButton.setEnabled(!isInstalled);
            installButton.setEnabled(!isInstalled);
            uninstallButton.setEnabled(isInstalled);
            startButton.setEnabled(isInstalled && !isRunning);
            stopButton.setEnabled(isInstalled && isRunning);
        } else {
            downloadButton.setEnabled(false);
            installButton.setEnabled(false);
            uninstallButton.setEnabled(false);
            startButton.setEnabled(false);
            stopButton.setEnabled(false);
        }
    }
    
    /**
     * 下载插件
     */
    private void downloadPlugin() {
        PluginInfo selected = pluginList.getSelectedValue();
        if (selected == null) return;
        
        new SwingWorker<Void, Void>() {
            private Exception error;
            
            @Override
            protected Void doInBackground() throws Exception {
                try {
                    log("开始下载插件: " + selected.getName());
                    pluginManager.downloadPlugin(selected.getDownloadUrl());
                } catch (Exception e) {
                    error = e;
                }
                return null;
            }
            
            @Override
            protected void done() {
                if (error != null) {
                    log("下载失败: " + error.getMessage());
                    JOptionPane.showMessageDialog(
                        PluginManagerGUI.this,
                        "下载插件失败: " + error.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                    );
                } else {
                    log("插件下载成功");
                }
            }
        }.execute();
    }
    
    /**
     * 安装选中的插件
     */
    private void installSelectedPlugin() {
        PluginInfo selected = pluginList.getSelectedValue();
        if (selected == null) return;
        
        new SwingWorker<Void, Void>() {
            private Exception error;
            
            @Override
            protected Void doInBackground() throws Exception {
                try {
                    log("开始安装插件: " + selected.getName());
                    pluginManager.installPlugin(selected.getId());
                } catch (Exception e) {
                    error = e;
                }
                return null;
            }
            
            @Override
            protected void done() {
                if (error != null) {
                    log("安装失败: " + error.getMessage());
                    JOptionPane.showMessageDialog(
                        PluginManagerGUI.this,
                        "安装插件失败: " + error.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                    );
                } else {
                    log("插件安装成功");
                }
            }
        }.execute();
    }
    
    /**
     * 卸载选中的插件
     */
    private void uninstallSelectedPlugin() {
        PluginInfo selected = pluginList.getSelectedValue();
        if (selected == null) return;
        
        int confirm = JOptionPane.showConfirmDialog(
            this,
            "确定要卸载 " + selected.getName() + " 吗？",
            "确认卸载",
            JOptionPane.YES_NO_OPTION
        );
        
        if (confirm == JOptionPane.YES_OPTION) {
            new SwingWorker<Void, Void>() {
                private Exception error;
                
                @Override
                protected Void doInBackground() throws Exception {
                    try {
                        log("开始卸载插件: " + selected.getName());
                        pluginManager.uninstallPlugin(selected.getId());
                    } catch (Exception e) {
                        error = e;
                    }
                    return null;
                }
                
                @Override
                protected void done() {
                    if (error != null) {
                        log("卸载失败: " + error.getMessage());
                        JOptionPane.showMessageDialog(
                            PluginManagerGUI.this,
                            "卸载插件失败: " + error.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                        );
                    } else {
                        log("插件卸载成功");
                    }
                }
            }.execute();
        }
    }
    
    /**
     * 启动选中的插件
     */
    private void startSelectedPlugin() {
        PluginInfo selected = pluginList.getSelectedValue();
        if (selected == null) return;
        
        new SwingWorker<Void, Void>() {
            private Exception error;
            
            @Override
            protected Void doInBackground() throws Exception {
                try {
                    log("开始启动插件: " + selected.getName());
                    pluginManager.startPlugin(selected.getId());
                } catch (Exception e) {
                    error = e;
                }
                return null;
            }
            
            @Override
            protected void done() {
                if (error != null) {
                    log("启动失败: " + error.getMessage());
                    JOptionPane.showMessageDialog(
                        PluginManagerGUI.this,
                        "启动插件失败: " + error.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                    );
                } else {
                    log("插件启动成功");
                }
            }
        }.execute();
    }
    
    /**
     * 停止选中的插件
     */
    private void stopSelectedPlugin() {
        PluginInfo selected = pluginList.getSelectedValue();
        if (selected == null) return;
        
        new SwingWorker<Void, Void>() {
            private Exception error;
            
            @Override
            protected Void doInBackground() throws Exception {
                try {
                    log("开始停止插件: " + selected.getName());
                    pluginManager.stopPlugin(selected.getId());
                } catch (Exception e) {
                    error = e;
                }
                return null;
            }
            
            @Override
            protected void done() {
                if (error != null) {
                    log("停止失败: " + error.getMessage());
                    JOptionPane.showMessageDialog(
                        PluginManagerGUI.this,
                        "停止插件失败: " + error.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                    );
                } else {
                    log("插件停止成功");
                }
            }
        }.execute();
    }
    
    /**
     * 更新服务状态面板
     */
    private void updateServiceStatus() {
        SwingUtilities.invokeLater(() -> {
            serviceStatusPanel.removeAll();
            
            Map<String, String> activeServices = serviceManager.getActiveServiceInfo();
            for (Map.Entry<String, String> entry : activeServices.entrySet()) {
                String serviceType = entry.getKey();
                String serviceInfo = entry.getValue();
                
                // 简化服务类型名称，只显示类名
                String simpleTypeName = serviceType.substring(serviceType.lastIndexOf('.') + 1);
                
                JLabel label = new JLabel(simpleTypeName + ": " + serviceInfo);
                serviceStatusPanel.add(label);
            }
            
            serviceStatusPanel.revalidate();
            serviceStatusPanel.repaint();
        });
    }
    
    /**
     * 记录日志，使用当前激活的日志服务
     */
    private void log(String message) {
        LogService logService = serviceManager.getService(LogService.class);
        logService.info(message);
        
        // 同时在界面日志区域显示
        SwingUtilities.invokeLater(() -> {
            logArea.append(new Date().toString() + " - " + message + "\n");
            logArea.setCaretPosition(logArea.getDocument().getLength());
        });
    }
    
    /**
     * 插件列表单元格渲染器，显示不同状态
     */
    private class PluginListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value,
                                                      int index, boolean isSelected,
                                                      boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            
            if (value instanceof PluginInfo) {
                PluginInfo info = (PluginInfo) value;
                Plugin plugin = pluginManager.getPluginById(info.getId());
                
                if (plugin != null) {
                    boolean isRunning = pluginManager.isPluginRunning(info.getId());
                    setText(info.getName() + " (" + info.getVersion() + ")");
                    
                    if (isRunning) {
                        setForeground(Color.GREEN);
                    } else {
                        setForeground(Color.BLUE);
                    }
                } else {
                    setText(info.getName() + " (" + info.getVersion() + ")");
                    setForeground(Color.BLACK);
                }
            }
            
            return this;
        }
    }
}
